package cc.smarnet.caihou.cheng;
import cc.smarnet.caihou.R;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainDemoActivity extends AppCompatActivity {
    private final static String TAG = MainDemoActivity.class.getSimpleName();
    final Boolean SendMoudle=true;  //  这个表示是连接称重模块
    Boolean bisClosed=false;
    public  ScaleView scaleView;
    Bundle bundle;
    private Button mButton_Zero;
    private Button mButton_Tare;
    private Button mButton_Unit;

    public Button mButton_SearchBluetooth;

    /**    BLE ն */
    private BluetoothAdapter mBluetoothAdapter;
    /**  дBLE ն */
    private Bluetooth_Scale mBl_Scale=null;
    private BluetoothDevice device;
    Handler mHandler;
    Boolean b_scaleIsConnect=Boolean.FALSE;
    SCALENOW scalenow=new SCALENOW();
    String BluetoothAddress;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView( R.layout.chengdemo_activity_main);
        // If the adapter is null, then Bluetooth is not supported
        // Initializes a Bluetooth adapter.  For API level 18 and above, get a reference to
        // BluetoothAdapter through BluetoothManager.
        Log.e(TAG, "++ ON Create ++");
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        // Checks if Bluetooth is supported on the device.
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_LONG).show();
            finish();
            return;
        }

        mHandler=new Handler()
        {
            public void handleMessage(Message msg)
            {
                switch(msg.what)
                {
                    case 1:
                        bundle=msg.getData();
                        GetWeight(bundle.getByteArray("weight"));
                        scaleView.setUnit(scalenow.sUnit);
                        if(scalenow.bOverFlag)
                        {
                            scaleView.setText("over----");
                        }
                        else {
                            scaleView.setText(scalenow.sformatNetWeight);
                        }

                        scaleView.setZero(scalenow.bZeroFlag);
                        scaleView.setStable(scalenow.bWeiStaFlag);
                        break;
                    case 2:
                        if(msg.arg1<2) {
                            scaleView.setText(getString(R.string.NoConnect));
                            b_scaleIsConnect=Boolean.FALSE;
                        }
                        else {
                            b_scaleIsConnect = Boolean.TRUE;
                            if(SendMoudle)
                            {
                                scaleView.setText("已连接");
                                mBl_Scale.write("RN1\r\n".getBytes());    //模块需要发送RN1表示连续读净重
                            }
                        }
                        break;

                }
            }
        };
        mBluetoothAdapter.enable();
        mBl_Scale = new Bluetooth_Scale(this,mHandler);
        scaleView=(ScaleView)findViewById(R.id.scaleView111);


        mButton_Zero=(Button)findViewById(R.id.Button_Zerodemo);
        mButton_Tare=(Button)findViewById(R.id.Button_Taredemo);
        mButton_Unit=(Button)findViewById(R.id.Button_Unitdemo);
        mButton_SearchBluetooth=(Button)findViewById(R.id.Button_Search);
        mButton_SearchBluetooth.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // TODO Auto-generated method stub

                Intent serverIntent = new Intent(MainDemoActivity.this, DeviceListActivity.class);
                startActivityForResult(serverIntent, 0);
            }
        });

        mButton_Zero.setOnClickListener(new View.OnClickListener(){
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                if((mBl_Scale !=null)&&b_scaleIsConnect)
                {
                    Log.d(TAG, "Zero");
                    mBl_Scale.write("SZ09\r\n".getBytes());
                }
            }
        });


        mButton_Tare.setOnClickListener(new View.OnClickListener(){

            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                if((mBl_Scale !=null)&& b_scaleIsConnect)
                {
                    mBl_Scale.write("ST07\r\n".getBytes());
                }
            }
        });
        mButton_Unit.setOnClickListener(new View.OnClickListener(){
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                if((mBl_Scale !=null)&& b_scaleIsConnect)
                {
                    mBl_Scale.write("SU06\r\n".getBytes());
                }
            }
        });


    }
    @Override
    public void onConfigurationChanged(Configuration config) {
        super.onConfigurationChanged(config);
        Log.e(TAG, "++ ON ConfigurationChanged ++");
    }
    @Override
    public void onStart() {
        super.onStart();
        Log.e(TAG, "++ ON START ++");

        // If BT is not on, request that it be enabled.
        // setupChat() will then be called during onActivityResult


    }
    @Override
    public synchronized void onResume() {
        super.onResume();
        Log.e(TAG, "+ ON RESUME +");

        // Performing this check in onResume() covers the case in which BT was
        // not enabled during onStart(), so we were paused to enable it...
        // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
        if (mBl_Scale != null) {
            Log.e(TAG, "+ Not null +");
            // Only if the state is STATE_NONE, do we know that we haven't started already
            if (mBl_Scale.getState() == Bluetooth_Scale.STATE_NONE) {
                // Start the Bluetooth chat services
                if(BluetoothAddress!=null)
                {
                    Log.e(TAG, "+ Address Not null +");
                    // Get the BluetoothDevice object
                    // device= mBluetoothAdapter.getRemoteDevice(BluetoothAddress);
                    // if(device!=null)
                    // {
                    // mBl_Scale.connect(device);
                    // }
                }
            }
        }
    }
    @SuppressLint("SimpleDateFormat")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode)
        {
            case 0:
                if (resultCode == RESULT_OK) {
                    connectDevice(data);
                }
                break;

        }
    }
    private void connectDevice(Intent data) {
        // Get the device MAC address

        mBl_Scale.stop();		// ȶϿ ǰ       ,Ȼ    ʱһ        ,  ֤ǰ    Ѿ  Ͽ ,     ֱ     Ӳ      ӵ     һ   豸,   ʧ  ,
        BluetoothAddress= data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
        if(BluetoothAddress.length()>0)
        {
            // Get the BluetoothDevice object
            device= mBluetoothAdapter.getRemoteDevice(BluetoothAddress);
            if(device!=null)
            {
                mBl_Scale.connect(device);
            }
        }
    }

    @Override
    protected void onDestroy() {
        if (mBl_Scale != null) mBl_Scale.stop();
        bisClosed=true;
        super.onDestroy();
        //  System.exit(0);
    }
    public static int _dec(int l, int m, int n)
    {
        int    a=l, b=m, c=1;
        while(b!=0)
        {
            while((b & 1)==0)
            {
                b>>=1;
                a=(int) ((long)a*a%n);
            }
            b--;
            c=(int) ((long)a*c%n);
        }
        return c;
    }
    static byte ASCII2Bin(byte strdata)
    {
        if((strdata<='9')&&(strdata>='0'))return (byte) (strdata-'0');
        else if((strdata<='z')&&(strdata>='a'))return (byte) (strdata-'a'+10);
        else return (byte) (strdata-'A'+10);
    }
    static float HctWeightDecryption(byte buf[])
    {
        int r[]=new int[4];
        int ret;
        r[0]=(ASCII2Bin(buf[0])&0xf)*0x1000+(ASCII2Bin(buf[1])&0xf)*0x100
                +(ASCII2Bin(buf[2])&0xf)*0x10+(ASCII2Bin(buf[3])&0xf);
        r[1]=(ASCII2Bin(buf[4])&0xf)*0x1000+(ASCII2Bin(buf[5])&0xf)*0x100
                +(ASCII2Bin(buf[6])&0xf)*0x10+(ASCII2Bin(buf[7])&0xf);
        r[2]=(ASCII2Bin(buf[8])&0xf)*0x1000+(ASCII2Bin(buf[9])&0xf)*0x100
                +(ASCII2Bin(buf[10])&0xf)*0x10+(ASCII2Bin(buf[11])&0xf);
        r[3]=(ASCII2Bin(buf[12])&0xf)*0x1000+(ASCII2Bin(buf[13])&0xf)*0x100
                +(ASCII2Bin(buf[14])&0xf)*0x10+(ASCII2Bin(buf[15])&0xf);
        ret=((_dec(r[0], 47653, 39917)&0xff)<<24)+(_dec(r[1], 47653, 39917)&0xff)*0x10000+(_dec(r[2], 47653, 39917)&0xff)*0x100+_dec(r[3], 47653, 39917);
        float f = Float.intBitsToFloat(ret);
        return f;
    }

    void GetWeight(byte[] databuf)
    {
        int i,j,offset=6;
        String ShowFmtTab[]={"%1$8.0f","%1$8.1f","%1$8.2f","%1$8.3f","%1$8.4f","%1$8.5f","%1$8.6f","%1$8.6f","%1$8.6f"};
        boolean	StartFalg=false;
        scalenow.bZeroFlag=true;
        scalenow.bOverFlag=false;
        scalenow.bWeiStaFlag=false;
        switch(databuf[0])
        {
            case 'o':
            case 'O':
                scalenow.bOverFlag=true;
                break;
            case 'u':
            case 'U':
                scalenow.bWeiStaFlag=false;
                offset=6;	//6
                break;
            case 's':
            case 'S':
                scalenow.bWeiStaFlag=true;
                break;
        }
        /*byte[] weightbuf=new byte[16];
        for(i=0;i<16;i++) {
            weightbuf[i]=(byte)(databuf[offset+i]);
        }
        scalenow.formatNetWeight=HctWeightDecryption(weightbuf);
        j=(databuf[offset+16]-'0')/3;
        if((j>=0)&&(j<=9))scalenow.sformatNetWeight=String.format(ShowFmtTab[(databuf[offset+16]-'0')/3], scalenow.formatNetWeight);
        for(j=0;j<6;j++)
        {
            if(databuf[17+j+offset]<0x20)
            {
                break;
            }
        }
        scalenow.sUnit=new String(databuf,17+offset,j);
        */
        if(databuf[5]=='-')offset=5;
        for(i=0;i<14;i++)
        {
            if(databuf[i+offset]=='\'')databuf[i+offset]='.';
            if(StartFalg)
            {
                if(((databuf[i+offset]>'9')||(databuf[i+offset]<'.'))&&(!((databuf[i+offset]==' ')&&(databuf[i+offset+1]<='9'))))
                {
                    break;
                }
            }
            else if((databuf[i+offset]>='0')&&(databuf[i+offset]<='9'))
            {
                StartFalg=true;
                if(databuf[i+offset]!='0')scalenow.bZeroFlag=false;
            }
        }
        scalenow.sformatNetWeight=new String(databuf,offset,i);


        for(j=0;j<6;j++)
        {
            if(databuf[i+j+offset]<0x20)
            {
                break;
            }
        }
        scalenow.sUnit=new String(databuf,i+offset,j);

    }

    public static class SCALENOW {
        public float formatNetWeight;
        public String		sformatNetWeight="0";
        public String		sUnit="0";
        public boolean bWeiStaFlag;
        public boolean bZeroFlag;
        public boolean bOverFlag;
    }
}
